package mc.support.util;

import org.joda.time.DateTime;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA. <br/>
 * Author: francis Yun    <br/>
 * Date: 2013-12-10  <br/>
 */
public final class CronUtil {

    private static final int MINUTES_AHEAD = 1;

    private static final char ANY = '*';

    private static final char BLANK = ' ';

    private CronUtil() {}

    public static String getMonthlyFromNowPattern() {
        DateTime now = DateTime.now();
        int day = now.getDayOfMonth();
        int hour = now.getHourOfDay();
        int minute = now.getMinuteOfHour() + MINUTES_AHEAD;

        if ( 60 == minute ) {
            minute = 1;
            hour++;
        }

        return PlainUtil.connectToStr(
                minute, BLANK,
                hour, BLANK,
                day, BLANK,
                ANY, BLANK,
                ANY );
    }

    public static String getDailyPattern(int hour, int minute) {
        hour = hour % 23;
        minute = minute % 59;

        return PlainUtil.connectToStr(
                minute, BLANK,
                hour, BLANK,
                ANY, BLANK,
                ANY, BLANK,
                ANY );
    }

    public static int toIdentificationInt(Date d) {
        if ( null != d ) {
            DateTime dt = new DateTime( d );
            int month = dt.getMonthOfYear();
            int day = dt.getDayOfMonth();
            int hour = dt.getHourOfDay();
            int min = dt.getMinuteOfHour();
            int sec = dt.getSecondOfMinute();

            return ( sec & 0x3F ) |
                   ( min << 6 & 0xFC0 ) |
                   ( hour << 12 & 0x1F000 ) |
                   ( day << 17 & 0x3E0000  ) |
                   ( month << 22 & 0x3C00000 )
                    ;
        }
        return 0;
    }

    public static void main(String...s) throws InterruptedException {
        printBytes( toIdentificationInt( new Date() ) );
        TimeUnit.SECONDS.sleep(1);
        printBytes( toIdentificationInt( new Date() ) );
        TimeUnit.SECONDS.sleep(1);
        printBytes( toIdentificationInt( new Date() ) );
    }
    
    private static void printBytes(int i) {
        System.out.println( Integer.toBinaryString( i ));
    }

}
